//
//  yxpMBHUD.m
//  TestProject
//
//  Created by 杨小平 on 14-8-19.
//  Copyright (c) 2014年 yangxiaoping. All rights reserved.
//

#import "yxpMBHUD.h"
#import "MBProgressHUD.h"

#define BUTTON_TAG_MIN 3000
#define BUTTON_HEIGHT 40

@interface yxpMBHUD ()<MBProgressHUDDelegate>
{
    NSArray *_TextArray;
    MBProgressHUD *HUD;
    
    long long expectedLength;
	long long currentLength;
    
    NSMutableData *_data;
    UIImageView *_imageView;
}

@end

@implementation yxpMBHUD

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}
- (void)initView
{
    _imageView=[[UIImageView alloc] initWithFrame:self.view.bounds];
    _imageView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:_imageView];
    
    _TextArray=[[NSArray alloc] initWithObjects:@"纯指示器",@"带Label",@"带Label和详情",@"圆盘进度",@"圆环进度",@"大型进度条",@"自定义视图",@"多种结合",@"block实现",@"加载在window上",@"网络文件下载",@"背景虚化",@"纯文字",@"自定义颜色", nil];
    
    for (NSString *string in _TextArray) {
        
        UIButton *button=[[UIButton alloc] init];
        NSInteger index=[_TextArray indexOfObject:string];
        
        button.tag=BUTTON_TAG_MIN+index;
        
        CGRect rect;
        if (index%2==0) {
            rect.origin.x=10.0f;
        }else
        {
            rect.origin.x=165.0f;
        }
        
        rect.origin.y=index/2*(BUTTON_HEIGHT+10)+74;
        rect.size.width=145.0f;
        rect.size.height=BUTTON_HEIGHT;
        button.frame=rect;
        
        [button setTitleColor:[UIColor skyBlueColor] forState:UIControlStateNormal];
        [button setTitle:string forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        button.layer.borderColor=[[UIColor skyBlueColor] CGColor];
        button.layer.borderWidth=1.0f;
        button.layer.cornerRadius=5.0f;
        button.layer.masksToBounds=YES;
        [button addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:button];
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	
    [self initView];
}

- (void)clickButton:(UIButton *)button
{
    _imageView.image=nil;
    [self.view setNeedsDisplay];
    
    NSInteger index=button.tag-BUTTON_TAG_MIN;
    switch (index) {
        case 0:
            [self showSimple:button];
            break;
        case 1:
            [self showWithLabel:button];
            break;
        case 2:
            [self showWithDetailsLabel:button];
            break;
        case 3:
            [self showWithLabelDeterminate:button];
            break;
        case 4:
            [self showWIthLabelAnnularDeterminate:button];
            break;
        case 5:
            [self showWithLabelDeterminateHorizontalBar:button];
            break;
        case 6:
            [self showWithCustomView:button];
            break;
        case 7:
            [self showWithLabelMixed:button];
            break;
        case 8:
            [self showUsingBlocks:button];
            break;
        case 9:
            [self showOnWindow:button];
            break;
        case 10:
            [self showURL:button];
            break;
        case 11:
            [self showWithGradient:button];
            break;
        case 12:
            [self showTextOnly:button];
            break;
        case 13:
            [self showWithColor:button];
            break;
            
        default:
            break;
    }
}

//
- (void)showSimple:(id)sender {
	
	HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:HUD];
	HUD.delegate = self;
	//显示HUD并创建一个新的线程，在线程内容执行结束后调用delegate 的隐藏方法hudWasHidden:
	[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}
- (void)showWithLabel:(id)sender {
	
	HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:HUD];
	HUD.delegate = self;
	HUD.labelText = @"加载中...";
	[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}
- (void)showWithDetailsLabel:(id)sender {
	
	HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:HUD];
	
	HUD.delegate = self;
	HUD.labelText = @"加载中...";
	HUD.detailsLabelText = @"刷新数据";
	HUD.square = YES;
	
	[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}
- (void)showWithLabelDeterminate:(id)sender {
	
	HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:HUD];
	// 圆盘进度模型
	HUD.mode = MBProgressHUDModeDeterminate;
	HUD.delegate = self;
	HUD.labelText = @"加载中...";
	// myProgressTask uses the HUD instance to update progress
	[HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
}

- (void)showWIthLabelAnnularDeterminate:(id)sender {
	HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:HUD];
	// 圆圈数据模型
	HUD.mode = MBProgressHUDModeAnnularDeterminate;
	HUD.delegate = self;
	HUD.labelText = @"加载中...";
	[HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
}

- (void)showWithLabelDeterminateHorizontalBar:(id)sender {
	
	HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:HUD];
	
	// Set determinate bar mode
	HUD.mode = MBProgressHUDModeDeterminateHorizontalBar;
	
	HUD.delegate = self;
	
	// myProgressTask uses the HUD instance to update progress
	[HUD showWhileExecuting:@selector(myProgressTask) onTarget:self withObject:nil animated:YES];
}

- (void)showWithCustomView:(id)sender {
	
	HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:HUD];
	
	// The sample image is based on the work by http://www.pixelpressicons.com, http://creativecommons.org/licenses/by/2.5/ca/
	// Make the customViews 37 by 37 pixels for best results (those are the bounds of the build-in progress indicators)
	HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]];
	
	// Set custom view mode
	HUD.mode = MBProgressHUDModeCustomView;
	
	HUD.delegate = self;
	HUD.labelText = @"完成";
	
	[HUD show:YES];
	[HUD hide:YES afterDelay:3];
}

- (void)showWithLabelMixed:(id)sender {
	
	HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
	[self.navigationController.view addSubview:HUD];
	
	HUD.delegate = self;
	HUD.labelText = @"连接中...";
	HUD.minSize = CGSizeMake(135.f, 135.f);
	
	[HUD showWhileExecuting:@selector(myMixedTask) onTarget:self withObject:nil animated:YES];
}

- (void)showUsingBlocks:(id)sender {
#if NS_BLOCKS_AVAILABLE
	MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
	[self.navigationController.view addSubview:hud];
	hud.labelText = @"block实现效果";
	
	[hud showAnimated:YES whileExecutingBlock:^{
		[self myTask];
	} completionBlock:^{
		[hud removeFromSuperview];
	}];
#endif
}

- (void)showOnWindow:(id)sender {
	// The hud will dispable all input on the window
	HUD = [[MBProgressHUD alloc] initWithView:self.view.window];
	[self.view.window addSubview:HUD];
	
	HUD.delegate = self;
	HUD.labelText = @"加载中...";
	
	[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}

- (void)showURL:(id)sender {
	NSURL *URL = [NSURL URLWithString:@"http://a.hiphotos.baidu.com/image/pic/item/d53f8794a4c27d1e3a6ce6c419d5ad6eddc4386c.jpg"];
	NSURLRequest *request = [NSURLRequest requestWithURL:URL];
	
	NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	[connection start];
	
	HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
	HUD.delegate = self;
}


- (void)showWithGradient:(id)sender {
	
	HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:HUD];
	HUD.dimBackground = YES;
	// Regiser for HUD callbacks so we can remove it from the window at the right time
	HUD.delegate = self;
	
	// Show the HUD while the provided method executes in a new thread
	[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}

- (void)showTextOnly:(id)sender {
	
	MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
	
	// Configure for text only and offset down
	hud.mode = MBProgressHUDModeText;
	hud.labelText = @"加载中...";
	hud.margin = 10.f;
	hud.removeFromSuperViewOnHide = YES;
	
	[hud hide:YES afterDelay:3];
}

- (void)showWithColor:(id)sender{
	HUD = [[MBProgressHUD alloc] initWithView:self.view];
	[self.view addSubview:HUD];
	
	// Set the hud to display with a color
	HUD.color = [[UIColor skyBlueColor] colorWithAlphaComponent:0.5];
	
	HUD.delegate = self;
	[HUD showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
}


#pragma mark - Execution code

- (void)myTask {
	// Do something usefull in here instead of sleeping ...
	sleep(2);
}

- (void)myProgressTask {
	// This just increases the progress indicator in a loop
	float progress = 0.0f;
	while (progress < 1.0f) {
		progress += 0.01f;
		HUD.progress = progress;
		usleep(50000);
	}
}

- (void)myMixedTask {
	// Indeterminate mode
	sleep(2);
	// Switch to determinate mode
	HUD.mode = MBProgressHUDModeDeterminate;
	HUD.labelText = @"正在连接...";
	float progress = 0.0f;
	while (progress < 1.0f)
	{
		progress += 0.01f;
		HUD.progress = progress;
		usleep(50000);
	}
	// Back to indeterminate mode
	HUD.mode = MBProgressHUDModeIndeterminate;
	HUD.labelText = @"开始清理";
	sleep(2);
	// UIImageView is a UIKit class, we have to initialize it on the main thread
	__block UIImageView *imageView;
	dispatch_sync(dispatch_get_main_queue(), ^{
		UIImage *image = [UIImage imageNamed:@"37x-Checkmark.png"];
		imageView = [[UIImageView alloc] initWithImage:image];
	});
	HUD.customView =imageView;
	HUD.mode = MBProgressHUDModeCustomView;
	HUD.labelText = @"完成";
	sleep(2);
}

#pragma mark - NSURLConnectionDelegete  在下载的时候会调用
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	expectedLength = MAX([response expectedContentLength], 1);
	currentLength = 0;
	HUD.mode = MBProgressHUDModeDeterminate;
    
    _data=[NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	currentLength += [data length];
    //获取下载进度
	HUD.progress = currentLength / (float)expectedLength;
    [_data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	HUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]];
	HUD.mode = MBProgressHUDModeCustomView;
	[HUD hide:YES afterDelay:2];
    
    UIImage *image=[UIImage imageWithData:_data];
    _imageView.image=image;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[HUD hide:YES];
}


#pragma mark - MBProgressHUDDelegate
- (void)hudWasHidden:(MBProgressHUD *)hud {
	// Remove HUD from screen when the HUD was hidded
	[HUD removeFromSuperview];
	HUD = nil;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    _imageView=nil;
    _data=nil;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
